﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MotionBlurWithDepthTexture : PostEffectsBase
{
    // 运动模糊Shader
    public Shader motionBlurShader;
    // 运动模糊材质
    private Material motionBlurMaterial = null;
    public Material material
    {
        get
        {
            motionBlurMaterial = CheckShaderAndCreateMaterial(motionBlurShader, motionBlurMaterial);
            return motionBlurMaterial;
        }
    }

    // 定义运动模糊是模糊图像的大小
    [Range(0.0f, 1.0f)]
    public float blurSize = 0.5f;

    // 需要借助相机的视角和投影矩阵
    private Camera myCamera;
    public Camera camera
    {
        get
        {
            if (myCamera == null) myCamera = GetComponent<Camera>();
            return myCamera;
        }
    }

    // 上一帧相机的视角*投影矩阵
    private Matrix4x4 matrixPreviousViewProjection;

    void OnEnable()
    {
        // 为了获取相机的深度纹理
        camera.depthTextureMode |= DepthTextureMode.Depth;
    }

    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        if (material != null)
        {
            material.SetFloat("_BlurSize", blurSize);

            // 将上一帧相机的视角*投影矩阵传入Shader
            material.SetMatrix("_PreviousViewProjectionMatrix", matrixPreviousViewProjection);

            // 计算当前帧相机的视角*投影矩阵
            Matrix4x4 matrixCurrentViewProjection = camera.projectionMatrix * camera.worldToCameraMatrix;
            Matrix4x4 matrixCurrentViewProjectionInverse = matrixCurrentViewProjection.inverse;
            // 将矩阵传入Shader
            material.SetMatrix("_CurrentViewProjectionInverseMatrix", matrixCurrentViewProjectionInverse);
            matrixPreviousViewProjection = matrixCurrentViewProjection;

            Graphics.Blit(src, dest, material);
        }
        else
        {
            Graphics.Blit(src, dest);
        }
    }
}